package memorphic.slide.debugger.controllers
{
	import flash.events.AsyncErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;
	
	import memorphic.logging.LogType;
	import memorphic.slide.StateManager;
	import memorphic.slide.debugger.IDebuggerAppContext;
	
	import mx.logging.Log;
	
	public class DebuggerController
	{
		
		private static var registeredApps:Array = [];
		
		private var newAppListener:LocalConnection;
		private var stateManager:StateManager;
		private var rootView:IDebuggerAppContext;
		
		public function DebuggerController(stateManager:StateManager, rootView:IDebuggerAppContext)
		{
			initNewAppListener();
			this.stateManager = stateManager;
			this.rootView = rootView;
		}


		private function initNewAppListener():void
		{
			newAppListener = new LocalConnection();
			newAppListener.allowDomain("*");
			newAppListener.connect("_slide_debugger");
			newAppListener.client = this;
			newAppListener.addEventListener(StatusEvent.STATUS, onAppListenerStatus);
			newAppListener.addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAppListenerAsyncError);
			newAppListener.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onAppListenerSecurityError);
			
			Log.getLogger(LogType.GENERAL).info("init LC");
		}
			
		private function onAppListenerStatus(e:StatusEvent):void
		{
			Log.getLogger(LogType.NETWORK).info("Status: " +e.code);
		}

		private function onAppListenerSecurityError(e:SecurityErrorEvent):void
		{
			Log.getLogger(LogType.NETWORK).error("Security Error: " +e.text);
		}

		private function onAppListenerAsyncError(e:AsyncErrorEvent):void
		{
			Log.getLogger(LogType.NETWORK).info("Async Error: " +e.text);
		}
		
		
		public function showOverlay(show:Boolean=true):void
		{
			var currentApp:String = registeredApps[registeredApps.length-1];
			if(!currentApp){
				return;
			}
			var lc:LocalConnection = new LocalConnection();
			if(show){
				lc.send(currentApp, "highlightOn");
			}else{
				lc.send(currentApp, "highlightOff");
			}
		}
		
		
		public function registerApp(id:String):void
		{
			Log.getLogger(LogType.GENERAL).info("register app: " + id);
			registeredApps.push(id);
			rootView.availableApps = registeredApps.concat();
		}
	}
}


